package com.tgz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tgz.alisms.SmsUtil;
import com.tgz.mapper.PhoneMapper;
import com.tgz.model.Phone;
import com.tgz.service.IPhoneService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 手机号码 服务实现类
 * </p>
 *
 * @author hsj
 * @since 2022-12-22
 */
@Service
public class PhoneServiceImpl extends ServiceImpl<PhoneMapper, Phone> implements IPhoneService {

//    @Autowired
//    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public List<Phone> findAllPhone() {
        return baseMapper.findAllPhone();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Integer addPhoneUnique(String phone) throws Exception {
        if (StringUtils.isEmpty(phone)){
            throw new Exception("很抱歉，您输入的手机号不能为空！");
        }
        //去除空格
        phone = phone.trim();
        Integer countByPhoneActived = countByPhoneActived(phone);
        if(countByPhoneActived != null && countByPhoneActived > 0){
            throw new Exception("很抱歉，您输入的手机号已经签到！");
        }
        Phone phoneEntity = new Phone();
        phoneEntity.setId(IdWorker.getId());
        phoneEntity.setPhone(phone);
        Integer count =  baseMapper.insert(phoneEntity);
        //异步发送短信
        if(count != null && count > 0){
            String phoneConstant = phone;
            CompletableFuture.runAsync(()->{
//                String code = RandomString.randomNumeric(4);
                SmsUtil.sendSms(phoneConstant/*, code*/);
            }/*,threadPoolTaskExecutor*/);
        }
        return count;
    }

    @Override
    public Integer countByPhoneActived(String phone) {
        return baseMapper.selectCount(new QueryWrapper<Phone>()
                .lambda()
                .eq(Phone::getPhone,phone)
                .eq(Phone::getIsDeleted, com.tgz.constant.Phone.IS_DELETED_0)
                .eq(Phone::getStatus, com.tgz.constant.Phone.STATUS_1)
        );
    }
}
